<?php

namespace App\Services;


use App\Models\MasterAccess;
use App\Models\MasterPermission;
use common\enum\CommonEnum;
use Illuminate\Support\Facades\Auth;

class AccessService
{
    public static function accessList($menuId)
    {
        $admin = Auth::user();
        $operateRoleId = $admin['role'];
        $query = MasterAccess::select()->where(['menu_id' => $menuId]);
        if ($operateRoleId != CommonEnum::ADMIN_ROLE_ID) {
            //获得该角色所有操作
            $accessIds = MasterPermission::selectRaw('DISTINCT `access_id` as access_id')
                ->where([
                    'role_id' => $operateRoleId,
                    'menu_id' => $menuId
                ])
                ->pluck('access_id')
                ->toArray();
            $query->whereIn('id', $accessIds);
        }
        $allAccess = $query->get()->toArray();
        return self::listToTree($allAccess, 0, 'pid', 'id', true);
    }

    //转为树状结构
    public static function listToTree($list, $pid, $pidKey = 'pid', $idKey = 'id', $hasChild = false)
    {
        $arr = [];
        foreach ($list as $leaf) {
            if ($leaf[$pidKey] == $pid) {
                $children = self::listToTree($list, $leaf[$idKey], $pidKey, $idKey, $hasChild);
                if ($hasChild) {
                    $leaf['children'] = $children;
                } elseif (!empty($children)) {
                    $leaf['children'] = $children;
                }
                $arr[] = $leaf;
            }
        }
        return $arr;
    }
}